#include "LtcGenerator.h"
#include "ltc.h"
#include <QTimer>
#include <QTime>

LtcGenerator::LtcGenerator()
{
	init();
}

LtcGenerator::~LtcGenerator()
{
	ltc_encoder_free(m_encoder);
	delete m_timer;
}

void LtcGenerator::init()
{
	double length = 2; // in seconds
	double fps = 25;
	double sampleRate = 48000;

	int total = 0;


	SMPTETimecode st;

	const char timezone[6] = "+0100";

	strcpy_s(st.timezone, timezone);
	st.years = 8;
	st.months = 12;
	st.days = 31;

	QTime time = QTime::currentTime();
	st.hours = time.hour();
	st.mins = time.minute();
	st.secs = time.second();
	st.frame = time.msec() * 25;

	m_encoder = ltc_encoder_create(1, 1, LTC_TV_525_60, LTC_USE_DATE);
	ltc_encoder_set_buffersize(m_encoder, sampleRate, fps);
	ltc_encoder_reinit(m_encoder, sampleRate, fps,
		fps == 25 ? LTC_TV_625_50 : LTC_TV_525_60, LTC_USE_DATE);

	ltc_encoder_set_filter(m_encoder, 0);
	ltc_encoder_set_filter(m_encoder, 25.0);
	ltc_encoder_set_volume(m_encoder, -18.0);

	ltc_encoder_set_timecode(m_encoder, &st);

	m_timer = new QTimer(this);
    connect(m_timer, &QTimer::timeout, [&]() {
		//for (int i = 0; i < 25; i++)
		{
			ltc_encoder_encode_frame(m_encoder);
			int len;
			ltcsnd_sample_t* buf;
			len = ltc_encoder_get_bufferptr(m_encoder, &buf, 1);

			if (len > 0) {
				QByteArray buff((char*)buf, len);
				emit productionOccurred(buff);
				total += len;
			}

			ltc_encoder_inc_timecode(m_encoder);
		}
		/*{
			SMPTETimecode st1;

			const char timezone[6] = "+0100";

			strcpy_s(st1.timezone, timezone);
			st1.years = 8;
			st1.months = 12;
			st1.days = 31;

			QTime time1 = QTime::currentTime();
			st1.hours = time.hour();
			st1.mins = time.minute();
			st1.secs = time.second();
			st1.frame = time.msec() * 25;

			LTCFrame frame1;
			ltc_time_to_frame(&frame1, &st1, LTC_TV_625_50, LTC_TC_CLOCK);
			ltc_encoder_set_frame(m_encoder, &frame1);
		}*/

		
    });
	m_timer->start(1000/25);
}